<template>
    <div class="house-list">
        <Header />
        
        <PageBanner
            title="房产列表"
            :breadcrumbs="[
                { title: '房产', path: '/house' },
                { title: '房产列表' }
            ]"
        />
        
        <!-- 主要内容区域 -->
        <div class="container">
            <div class="content-wrapper">
                <!-- 视图切换器 -->
                <ViewSwitcher
                    @viewChange="handleViewChange"
                    @categoryChange="handleCategoryChange"
                    @showFilter="showFilterModal"
                />
                
                <!-- 房产列表 -->
                <div :class="currentView === 'grid' ? 'house-grid' : 'house-list'">
                    <template v-if="currentView === 'grid'">
                        <HouseCard 
                            v-for="house in houses.list" 
                            :key="house.houseId" 
                            :house="house"
                            @click="handleHouseClick(house)"
                            @update:favorite="handleFavoriteUpdate"
                        />
                    </template>
                    <template v-else>
                        <HouseListItem
                            v-for="(house, index) in houses.list"
                            :key="house.houseId"
                            :house="house"
                            :reverse="index % 2 === 1"
                            @click="handleHouseClick(house)"
                        />
                    </template>
                </div>
                
                <!-- 加载中状态 -->
                <div v-if="loading" class="loading">
                    <el-loading />
                </div>
                
                <!-- 无数据展示 -->
                <div v-if="!loading && (!houses.list || houses.list.length === 0)" class="no-data">
                    <svg-icon name="common/no-data" />
                    <p>暂无相关房产</p>
                </div>
                
                <Pagination
                    v-if="houses.list && houses.list.length > 0"
                    v-model:currentPage="queryParams.current"
                    :total="houses.total"
                    :page-size="queryParams.size"
                    @current-change="handlePageChange"
                />
            </div>
        </div>
        
        <Footer />
        
        <!-- 筛选弹窗 -->
        <el-dialog
            v-model="filterDialogVisible"
            title="房产筛选"
            width="80%"
            destroy-on-close
        >
            <el-form :model="queryParams.filters" label-width="100px">
                <el-form-item label="价格区间">
                    <el-slider
                        v-model="queryParams.filters.priceRange"
                        range
                        :min="0"
                        :max="2000"
                        :step="10"
                    />
                </el-form-item>
                <el-form-item label="面积区间">
                    <el-slider
                        v-model="queryParams.filters.areaRange"
                        range
                        :min="0"
                        :max="500"
                        :step="10"
                    />
                </el-form-item>
                <el-form-item label="房屋类型">
                    <el-select v-model="queryParams.filters.houseType">
                        <el-option label="整租" value="1" />
                        <el-option label="合租" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="卧室数量">
                    <el-input-number v-model="queryParams.filters.bedroom" :min="1" :max="10" />
                </el-form-item>
                <el-form-item label="所在区域">
                    <el-select v-model="queryParams.filters.district">
                        <el-option label="朝阳区" value="朝阳区" />
                        <el-option label="海淀区" value="海淀区" />
                        <el-option label="东城区" value="东城区" />
                        <el-option label="西城区" value="西城区" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="filterDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleFilterConfirm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getHouseList, getHotHouses, getLatestHouses } from '@/api/house'
import Header from '@/views/common/Header.vue'
import Footer from '@/views/common/Footer.vue'
import HouseCard from './components/HouseCard.vue'
import HouseListItem from './components/HouseListItem.vue'
import ViewSwitcher from './components/ViewSwitcher.vue'
import Pagination from '@/views/common/Pagination.vue'
import { ElMessage, ElDialog, ElForm, ElFormItem, ElButton, ElSelect, ElOption, ElSlider, ElInputNumber, ElLoading } from 'element-plus'
import 'element-plus/dist/index.css'
import PageBanner from '@/views/common/PageBanner.vue'
import { enrichHousesWithAgentInfo } from '@/utils/agentHelper'

const router = useRouter()
const loading = ref(false)
const filterDialogVisible = ref(false)

// 查询参数
const queryParams = reactive({
    current: 1,
    size: 9,  // 默认网格视图9条
    filters: {
        priceRange: null,
        areaRange: null,
        houseType: null,
        propertyType: null,
        bedroom: null,
        district: null,
        subway: null,
        station: null,
        distance: null,
        orientation: null,
        decoration: null,
        tags: [],
        facilities: []
    },
    sort: {
        field: 'createTime',
        order: 'desc'
    }
})

// 房产数据
const houses = reactive({
    total: 0,
    pages: 0,
    current: 1,
    size: 9,
    list: []
})

const currentView = ref('grid')
const currentCategory = ref('all')

// 获取房产列表数据
const fetchHouses = async () => {
    loading.value = true
    try {
        const params = new URLSearchParams()
        
        // 只传递基础分页参数
        params.append('current', queryParams.current)
        params.append('size', queryParams.size)
        
        // 排序参数
        if (queryParams.sort.field) {
            params.append('sortField', queryParams.sort.field)
            params.append('sortOrder', queryParams.sort.order)
        }

        console.log('请求参数：', Object.fromEntries(params))
        
        const response = await getHouseList(params)
        if (response.code === 200) {
            // 先保存原始房源数据
            const houseList = response.data.records || []
            
            console.log('原始房源数据:', houseList.map(h => ({
                id: h.id || h.houseId,
                agentId: h.agentId,
                hasAgent: h.agentId ? '有经纪人ID' : '无经纪人ID'
            })))
            
            // 使用工具函数补充经纪人信息
            houses.list = await enrichHousesWithAgentInfo(houseList)
            
            houses.total = response.data.total || 0
            houses.pages = response.data.pages || 0
            houses.current = response.data.current || 1
            houses.size = response.data.size || 9
            
            console.log('房产列表数据（含经纪人信息）:', houses.list.map(h => ({
                id: h.id || h.houseId,
                agentId: h.agentId,
                agentName: h.agentName,
                hasAgent: h.agentId ? '有经纪人ID' : '无经纪人ID'
            })))
        } else {
            ElMessage.error(response.msg || '获取数据失败')
        }
    } catch (error) {
        console.error('获取房产列表失败:', error)
        ElMessage.error('获取数据失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

// 滚动到页面横幅位置
const scrollToBanner = () => {
    // 获取页面横幅元素
    const pageBanner = document.querySelector('.page-banner')
    if (pageBanner) {
        const rect = pageBanner.getBoundingClientRect()
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop
        const targetPosition = scrollTop + rect.top

        requestAnimationFrame(() => {
            window.scrollTo({
                top: targetPosition,
                behavior: 'smooth'
            })
        })
    }
}

// 处理视图切换
const handleViewChange = async (view) => {
    loading.value = true
    currentView.value = view
    // 切换视图时更新每页显示数量
    queryParams.size = view === 'grid' ? 9 : 3
    houses.size = queryParams.size
    queryParams.current = 1
    await fetchHouses()
    scrollToBanner()
}

// 处理分类切换
const handleCategoryChange = async (category) => {
    currentCategory.value = category
    queryParams.current = 1
    await fetchHouses()
    
    // 根据分类更新路由
    switch (category) {
        case 'hot':
            router.push('/house/hot')
            break
        case 'new':
            router.push('/house/new')
            break
        default:
            router.push('/house')
    }
}

// 处理页码变化
const handlePageChange = async (page) => {
    loading.value = true
    queryParams.current = page
    await fetchHouses()
    scrollToBanner()
}

// 处理筛选条件
const showFilterModal = () => {
    ElMessage.info('筛选功能暂时关闭，敬请期待')
    // filterDialogVisible.value = true  // 注释掉，暂时不显示筛选弹窗
}

// 处理筛选确认
const handleFilterConfirm = () => {
    filterDialogVisible.value = false
    // 暂时不执行筛选
    // queryParams.current = 1
    // fetchHouses()
}

// 处理房产点击
const handleHouseClick = (house) => {
    router.push({
        name: 'HouseDetail',
        params: { id: house.houseId }
    })
}

// 处理收藏更新
const handleFavoriteUpdate = ({ id, collected }) => {
    // 可以在这里更新其他相关视图，如果有需要的话
    console.log(`房源 ${id} 的收藏状态更新为: ${collected ? '已收藏' : '未收藏'}`)
}

// 初始化加载数据
onMounted(() => {
    fetchHouses()
})
</script>

<style lang="scss" scoped>
.house-list {
    width: 100%;
    display: flex;
    flex-direction: column;
    
    .page-banner {
        height: 240px;
        width: 100%;
        background: linear-gradient(rgba(74, 96, 161, 0.9), rgba(74, 96, 161, 0.8));
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 132px;
        
        .banner-content {
            text-align: center;
            color: #fff;
            
            h1 {
                font-size: 48px;
                font-weight: 600;
                margin-bottom: 16px;
            }
            
            .breadcrumb {
                font-size: 16px;
                
                a {
                    color: #fff;
                    text-decoration: none;
                    
                    &:hover {
                        opacity: 0.8;
                    }
                }
                
                .separator {
                    margin: 0 8px;
                    opacity: 0.8;
                }
                
                .current {
                    opacity: 0.8;
                }
            }
        }
    }
    
    .container {
        width: 100%;
        padding: 0 60px;
        box-sizing: border-box;
        margin: 60px auto;
        
        .content-wrapper {
            max-width: 1320px;
            margin: 0 auto;
            
            .house-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 24px;
                margin: 30px 0;
            }
            
            .house-list {
                display: flex;
                flex-direction: column;
                margin: 30px 0;
            }
            
            .loading {
                text-align: center;
                padding: 60px 0;
            }
            
            .no-data {
                text-align: center;
                padding: 60px 0;
                color: #6d737a;
                
                .svg-icon {
                    width: 120px;
                    height: 120px;
                    margin-bottom: 16px;
                }
                
                p {
                    font-size: 16px;
                }
            }
        }
    }
}
</style> 